const axios = require("axios").default;
const ComAxerrRes = require("../CommonAxerrHandler")
const qs = require("querystring");
const util = require("util");

class Babytree {
  constructor() {

  }

  /**
   * @description API被加密 参数不能随便改
   * @returns {Promise<{ok:Boolean,msg:String,data:{login_string:String}}>}
   */
  getLoginString() {
    return new Promise(resolve => {
      let post_data = `build_serial=3478f0960904&client_type=android&password=rOcaBbTFUS4ZmsP5FFKXOvpQ9wCeWOHjk4bQt08iTyDg984KOpEzy%2BOOB%2Fdy5C1%2BtU771OZGzRldxIjuVQY9sZ980uHXIPobQBm6kdL98BUrClhInoAaTj01DQPYKnZZb5yIXVyD1gv2xGXFanrzhYxFxXmGP8JPd3mfDIftKYhcOHN6UIoMDJvl%2Fqx53MZEZIbG21rye3WYcuTW8MrNHv86r9Cv88otZ1uHwR7B87Wc4RwICXovme3ueMKoXRRzuGTh0S0IkFC9hZXlQcV%2Ff5wmBMtQ23VPL72VcqfhhKmVtTo%2BRwd23d7uoW%2FyAvUbQ%2FkEkcW2iw6hxe04yERbGQ%3D%3D&current_baby_id=-1&local_ts=1549362629&app_id=pregnancy&longitude=&source_channel=xiaomi&babytree_net_type=1&version=7.9.27&bpreg_brithday=2017-02-05&phone_number=mSwbGp01guD2DjKYs3j4D3md0Xu2OJ2CkgHhaIm5bESObzpPtIbxOIPvlgVCrau09IbDFHAseu1f6xxa09O6%2F90cO57K7g2eGO9lvSG97DRWMq7tvq3anh%2B%2B3XMPz5cTBqU1cLwlNhxi9GlA66a8urbKm3pz0u4Oh4kIReCrH71lMF0fxXtSSCnHNtinON4zDjSl8QZMDnvKqQeHDIQ23BazA68na511WoBfajiBRHxl0MaMzzYSCJx0j5zQv7vJnlU928KOyUM%2F%2B4GW9G%2Bv1vzVewCvalFqRoA20vCRFGuYPtmHkLgRKyVM2mApNx7JaIq1nvwHr5EPbm1yAOecZw%3D%3D&device_model=Redmi%20Note%204X&latitude=&client_baby_status=3&ali_abtest_sample_id=9039&secret=cf796b10bf647ac5c81c8dc07f729f75&mac=80%3Aad%3A16%3A40%3Abb%3A93&client_role=2&babytree_client_type=android&download_ts=1549362390&bbtid=8282c48b1b424985&email=Fc%2FByxBQxyCBgEe7hIz2dNR767w8eNbpE6zZyU7l0pckdjd%2BAEiQkvu1SIQPk8fQR%2Borog9wuHPv9FjjnS0uVs8gI1w3IdWVqOYcmaSPCgUQeib2GDYJBukr9a37t%2FCSJ0q7ZwX6ptkc5x8ORKjZ80%2Fq%2B%2BRaupL33HHaVgjyJ3VIhFkQ6n5mbPHx%2BcMiVmyN%2Fwpcz4GzvikYVVjH37cE%2FVK5x8uQwQ51j63Quh3ohZXbA5cfWNE2ZjEpz2Gi2NaKnoqEpxB7Ufjtase3O%2B3PCaq7W3GZ9PjgFB27l3FDgpJIauc7AFaCdCWO3oYlyupgu6MkPtBBOyqICzVlh6tBCw%3D%3D`;
      axios.post("http://api.babytree.com/api/muser/login", post_data, {
        params: {
          build_serial: '3478f0960904',
          client_type: 'android',
          current_baby_id: -1,
          local_ts: 1549362629,
          app_id: "pregnancy",
          longitude: "",
          source_channel: "xiaomi",
          babytree_net_type: 1,
          version: '7.9.27',
          bpreg_brithday: '2017-02-05',
          device_model: 'Redmi+Note+4X',
          latitude: '',
          client_baby_status: 3,
          ali_abtest_sample_id: 9039,
          mac: '80:ad:16:40:bb:93',
          client_role: 2,
          "babytree_client_type": "android",
          "download_ts": "1549362390",
          "bbtid": "8282c48b1b424985",
          "ali_abtest_type": "118",
          "device_brand": "Xiaomi",
          "imei": "867787036075244",
          "android_id": "8282c48b1b424985"
        },
        headers: {
          "User-Agent": "okhttp/3.11.0"
        },
        validateStatus: s => s == 200
      }).then(axresp => {
        return resolve({
          ok: true,
          msg: "ok",
          data: {
            login_string: "u925602941763_112b4878257e3d96f719b130caa849b2_1549362631"
          }
        })
        if (axresp.data
          && axresp.data.status === "success"
          && axresp.data.data
          && axresp.data.data.login_string) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              login_string: axresp.data.data.login_string
            }
          })
        }
        throw new Error(`不符合预期:${util.inspect(axresp.data)}`)
      }).catch(axerr => {
        ComAxerrRes(resolve)(axerr);
      })
    })
  }

  /**
   * @return {Promise<{ok:Boolean,msg:String,data:{uptoken:String}}>}
   * @param {String} login_string 
   */
  getToken(login_string) {
    return new Promise(async resolve => {
      axios.get('http://api.babytree.com/wetime/mobile_qiniu/get_token', {
        params: {
          login_string: login_string
        },
        headers: {
          'Content-Type': "application/x-www-form-urlencoded",
          "user-agent": "okhttp/3.11.0",
        }
      }).then(axresp => {
        if (axresp.data
          && axresp.data.status === "success"
          && axresp.data.data
          && axresp.data.data.token) {
          return resolve({
            ok: true,
            msg: "ok",
            data: {
              uptoken: axresp.data.data.token
            }
          })
        }
        throw new Error(`No sanity resp:${util.inspect(
          axresp.data
        )}`)
      }).catch(axerr => {
        ComAxerrRes(resolve)(axerr);
      })
    })
  }

}
let babytree = new Babytree;
let p_loginString = babytree.getLoginString();


/**
  * @return {Promise<{ok:Boolean,msg:String,data:{uptoken:String}}>}
  * @param {String} login_string 
  */
function getToken() {
  return new Promise(async resolve => {
    let o_loginString = await p_loginString;
    if (!o_loginString.ok) {
      return resolve({
        ok: false,
        msg: `failed to login:${o_loginString.msg}`
      })
    }
    let o_token = await babytree.getToken(o_loginString.data.login_string);
    resolve({
      ok: o_token.ok,
      msg: o_token.msg,
      data: {
        uptoken: o_token.ok ? o_token.data.uptoken : ""
      }
    })
  })
}



module.exports = {
  _debug: {
    Babytree: Babytree
  },
  getToken: getToken
}